package com.car.token;

import com.car.exception.CustomException;
import org.json.JSONObject;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 党怡承
 * @since 2021-08-09
 * @description AccessToken访问令牌
 */
@Configuration
public class DetectionToken {
  /** 官网获取的API Key 更新为你的注册 */
  private static final String AK = "你自己申请的API Key";
  /** 官网获取的Secret Key 更新为你的注册 */
  private static final String SK = "你自己申请的Secret Key";

  public static String getToken() {
    try {
      String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
      String accessTokenURL =
          authHost + "grant_type=client_credentials" + "&client_id=" + AK + "&client_secret=" + SK;
      URL realUrl = new URL(accessTokenURL);
      HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
      connection.setConnectTimeout(3000);
      connection.setReadTimeout(3000);
      connection.setRequestMethod("GET");
      BufferedReader in =
          new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
      StringBuffer result = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        result.append(line);
      }
      JSONObject jsonObject = new JSONObject(result.toString());
      String access_token = jsonObject.getString("access_token");
      return access_token;
    } catch (Exception e) {
      throw new CustomException(20001,e.getMessage());
    }
  }
}
